import { Upload, Space, Image as AntdImage, Button, Popconfirm, Select, message, ColorPicker } from "antd";
import { useModel } from "umi";
import { useState, useEffect } from "react";
import ImgCrop from "antd-img-crop";
import Jdenticon from "react-jdenticon";

import useUpdateTypeIcon from "../../hooks/application/tools/useUpdateTypeIcon";

const EditApplicationTypeIcon = ({ application, type, reloadData }) => {
    const { defaultImageBase64, resourcePath } = useModel("global");
    const { kuboApi, kuboUrl } = useModel("kubo");
    const { onCloseGlobalModal } = useModel("global.modal");
    const { remoteOrganizationInfo } = useModel("organization.info");
    const { iconColors } = useModel("application.info");

    const { submitLoading, updateApplicationTypeIcon } = useUpdateTypeIcon();

    const [fileList, setFileList] = useState([]);
    const [newIcon, setNewIcon] = useState(false);
    const [backgroundColor, setBackgroundColor] = useState(type.appBgco || null);

    const setDefaultIcon = (e) => {
        e?.stopPropagation();
        let url = kuboUrl && type.appIcon ? kuboUrl + type.appIcon : "";
        setFileList([{ uid: "-1", name: "avatar.png", status: "done", url }]);
        setNewIcon(false);
    };

    useEffect(() => {
        setDefaultIcon();
    }, [kuboUrl, type.appIcon]);

    const handleChange = ({ fileList }) => {
        if (fileList.length > 0) {
            setFileList(fileList);
            setNewIcon(fileList[0].name !== "avatar.png");
        }
    };

    const saveIcon = async (e) => {
        e.stopPropagation();
        if (fileList[0]?.thumbUrl) {
            let filename = path.join(resourcePath, "image.png");
            var base64Data = fileList[0]?.thumbUrl.replace(/^data:image\/\w+;base64,/, "");
            var dataBuffer = Buffer.from(base64Data, "base64");
            try {
                fs.writeFileSync(filename, dataBuffer);
                const result = await kuboApi.add(fs.readFileSync(filename), { pin: false });
                const values = {
                    uniformSocialCreditCode: remoteOrganizationInfo.uniformSocialCreditCode,
                    appUuid: type.appUuid,
                    appType: type.appType,
                    appIcon: result.path,
                    appBgco: backgroundColor || null,
                };
                updateApplicationTypeIcon(values, (res) => {
                    if (res) {
                        message.success("成功更新应用客户端图标");
                        reloadData();
                        onCloseGlobalModal();
                    }
                });
                fs.unlinkSync(filename);
            } catch (error) {
                message.warning(error.toString());
            }
        }
    };

    let deleteLogo = async (e) => {
        e.stopPropagation();
        const values = {
            uniformSocialCreditCode: remoteOrganizationInfo.uniformSocialCreditCode,
            appUuid: type.appUuid,
            appType: type.appType,
            appIcon: null,
        };
        updateApplicationTypeIcon(values, (res) => {
            if (res) {
                message.success("成功更新应用客户端图标");
                reloadData();
                onCloseGlobalModal();
            }
        });
    };

    return (
        <div id="upload-avatar" style={{ marginTop: 20 }}>
            <ImgCrop>
                <Upload
                    ction={kuboUrl}
                    maxCount={1}
                    fileList={fileList}
                    listType="picture-card"
                    onChange={handleChange}
                    showUploadList={{ showDownloadIcon: false, showPreviewIcon: false, showRemoveIcon: false }}
                    itemRender={(originNode, file) => {
                        let url = file.thumbUrl || file.url || "";
                        return (
                            <div style={{ ...styles.avatarView, backgroundColor: backgroundColor || "#eee" }}>
                                {url ? (
                                    <AntdImage width={94} height={94} preview={false} src={url} fallback={defaultImageBase64} />
                                ) : (
                                    <Jdenticon size="94" value={application.appName || ""} />
                                )}
                            </div>
                        );
                    }}
                >
                    {newIcon ? (
                        <Space direction="vertical" size={10} style={{ marginLeft: 20 }}>
                            <Button loading={submitLoading} type="primary" style={{ width: 104 }} onClick={saveIcon}>
                                保存图标
                            </Button>
                            <Button loading={submitLoading} style={{ width: 104 }} onClick={setDefaultIcon}>
                                取消图标
                            </Button>
                        </Space>
                    ) : (
                        <Space direction="vertical" size={10} style={{ marginLeft: 20 }}>
                            <Button block type="primary" style={{ width: 104 }}>
                                更改图标
                            </Button>
                            {type.appIcon && (
                                <Popconfirm title="确认要删除图标信息吗?" okButtonProps={{ loading: false }} onConfirm={deleteLogo}>
                                    <Button block danger style={{ width: 104 }} onClick={(e) => e.stopPropagation()}>
                                        删除图标
                                    </Button>
                                </Popconfirm>
                            )}
                        </Space>
                    )}
                </Upload>
            </ImgCrop>

            <Space>
                <Select style={{ width: 200 }} placeholder="选背景颜色" value={backgroundColor} onChange={setBackgroundColor} optionLabelProp="label" allowClear>
                    {iconColors.map((item) => (
                        <Select.Option key={item} value={item} label={item}>
                            <Space>
                                <div style={{ width: 10, height: 10, backgroundColor: item }}></div>
                                <div>{item}</div>
                            </Space>
                        </Select.Option>
                    ))}
                </Select>

                <ColorPicker value={backgroundColor} onChange={(value, hex) => setBackgroundColor(hex)} />
            </Space>
        </div>
    );
};

const styles = {
    avatarView: {
        display: "inline-block",
        width: 104,
        height: 104,
        margin: 0,
        padding: 4,
        border: "1px solid #d9d9d9",
        borderRadius: 2,
    },
};

export default EditApplicationTypeIcon;
